package com.dhp.bkOjjudgeservice.codesandbox.utils;


import com.dhp.model.codesandbox.ExecuteMessage;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 控制台执行进程工具类
 */
public class ProcessUtil {


    /**
     * 执行进程并获取执行信息
     * @param process
     * @param opName
     * @return
     */
    public static ExecuteMessage executeAndGetMsg(Process process , String opName){
        ExecuteMessage executeMessage = new ExecuteMessage();
        try {
            int execCode = process.waitFor();
            executeMessage.setExecValue(execCode);
            if (execCode == 0) {
                System.out.println(opName + "成功");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                StringBuilder msgBuilder = new StringBuilder();
                String message;
                while ((message = bufferedReader.readLine()) != null) {
                    msgBuilder.append(message);
                }
                executeMessage.setExecuteMessage(msgBuilder.toString());
            } else {
                System.out.println(opName + "失败");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                StringBuilder msgBuilder = new StringBuilder();
                String message;
                while ((message = bufferedReader.readLine()) != null) {
                    msgBuilder.append(message);
                }
                executeMessage.setExecuteErrorMessage(msgBuilder.toString());
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return executeMessage;
    }
}
